package com.PopulateDB;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.TreeMap;

public class PopulateStates implements PopulateFormat{
	public static TreeMap<Integer, Integer> states = null;
	private static int stateTotal = 0;
	private static boolean simpleRandom = true;
	
	public boolean makeThing(DBPopulator db, int noOfStates) {
		if(this.remakeTable(db)){
			/*
			 *  If a negative value is passed then read all values
			 */
			if(noOfStates < 0)
				noOfStates = Integer.MAX_VALUE;
			states = new TreeMap<Integer, Integer>();
			
			/*
			 *  Open the states file
			 */
			InputStreamReader ins = new InputStreamReader(MakeAddress.class.getResourceAsStream(FileLocations.statesFile));
			BufferedReader in = new BufferedReader(ins);
			
			/*
			 *  Read in the values
			 */
			try {
				// Read and insert the states
				int inserted = 0;
				
				while(in.ready() && inserted <= noOfStates){
					// Read the line and insert it
					String[] state = in.readLine().split(",");
					int stateID = db.insertState(state[0], state[1]);
					
					// Get the number of entries for that state and add it to the total
					stateTotal += Integer.valueOf(state[2]);
					states.put(stateID, stateTotal);
					
					inserted++;
					System.out.println("Inserted " +state[0] + " as " + stateID);
				}
				
				System.out.println("read the lines of : " + FileLocations.statesFile);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public static int getRandomState(){
		if(simpleRandom){
			return ((int) Math.round(Math.random() * states.size())) + 1;
		}
		else{
			return -1;
		}
	}
	
	public boolean remakeTable(DBPopulator db) {
		return db.dropAddStates();
	}
}
